const util = require("../../utils/util")
const app = getApp()
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({
    options: {
        styleIsolation: 'shared'
    },
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            active: 'activeTabBarIndex'
        },
        actions: {
            updateActive: 'updateActiveTabBarIndex'
        },
    },
    
	data : {
		conversations : [],
		actionPopup : {
			visible : false,
			conversation : null
		},
		currentUser: {}
	},
	onShow () {
        // 使tabbar更新
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.updateActive(2)
        } 
		let currentUser = wx.getStorageSync('userInfo')
		if(!currentUser){
            util.myToastNone('请先登录～')
            this.setData({conversations: []})
			return
        }
        console.log('Goeasy connection status:', wx.goEasy.getConnectionStatus())
		this.setData({
            currentUser : currentUser,
            conversations: []
        })
		this.listenConversationUpdate()     //监听会话列表变化
		this.loadConversations()    //加载会话列表
	},
	onHide(){
		// 销毁conversation监听器
        wx.goEasy.im.on(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (conversations) => {})
    },
	// 加载最新的会话列表
	loadConversations() {
		wx.goEasy.im.latestConversations({
			onSuccess: (result) => {
				console.log('获取最新会话列表成功, result:', result);
				let content = result.content;
				this.renderConversations(content)
			},
			onFailed: (error) => {
				console.log('获取最新会话列表失败, error:', error);
			}
		});
    },
    // 监听会话列表变化
	listenConversationUpdate() {
		wx.goEasy.im.on(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
			this.renderConversations(content);
		});
    },
    // 置顶消息
	topConversation(){
		let self = this;
		let conversation = this.data.actionPopup.conversation;
		let failedDescription = conversation.top ? '取消置顶失败' : '置顶失败';
		wx.showLoading({title: '加载中...',mask: true});
		if(conversation.type === wx.GoEasy.IM_SCENE.PRIVATE){
			wx.goEasy.im.topPrivateConversation({
				userId: conversation.userId,
				top: !conversation.top,
				onSuccess: function () {
					wx.hideLoading();
				},
				onFailed: function (error) {
					self.showToast(failedDescription);
					console.log(error);
				}
			});
		}else{
			wx.goEasy.im.topGroupConversation({
				groupId: conversation.groupId,
				top: !conversation.top,
				onSuccess: function () {
					wx.hideLoading();
				},
				onFailed: function (error) {
					self.showToast(failedDescription);
					console.log(error);
				}
			});
		}
		this.closeMask();
	},
	removeConversation(){
		wx.showLoading({title: '加载中...',mask: true});
		let self = this;
		let failedDescription = '删除失败';
		let conversation = this.data.actionPopup.conversation;
		if(conversation.type ===  wx.GoEasy.IM_SCENE.PRIVATE){
			wx.goEasy.im.removePrivateConversation({
				userId: conversation.userId,
				onSuccess: function () {
					wx.hideLoading();
				},
				onFailed: function (error) {
					self.showToast(failedDescription);
					console.log(error);
				}
			});
		}else {
			wx.goEasy.im.removeGroupConversation({
				groupId: conversation.groupId,
				onSuccess: function () {
					wx.hideLoading();
				},
				onFailed: function (error) {
					self.showToast(failedDescription);
					console.log(error);
				}
			});
		}
		this.closeMask();
	},
	renderConversations (conversations) {
		conversations.conversations && conversations.conversations.map((item) => {
			// 格式化时间格式
			item.lastMessage.date = app.formatDate(item.lastMessage.timestamp)
		});
		this.setData({
			conversations : conversations.conversations
		});
		
	},
	navigateToChat (e) {
        if (!wx.getStorageSync('userInfo')) {
            util.myToastNone('请先登录～')
            return
        }
		let conversation = e.currentTarget.dataset.conversation;
		wx.navigateTo({url : '/pages/privateChat/privateChat?to=' + conversation.userId});
	},
	showAction(e){
		let conversation = e.currentTarget.dataset.conversation;
		this.setData({
			['actionPopup.conversation']: conversation,
			['actionPopup.visible']: true
		});
	},
	showToast (failedDescription) {
		wx.hideLoading();
		wx.showToast({
			title: failedDescription,
			duration: 3000,
			icon: 'none'
		});
	},
	closeMask(){
		// 关闭弹窗
		this.setData({
			['actionPopup.visible']: false
		})
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        wx.showNavigationBarLoading()
        setTimeout(() => {
            wx.hideNavigationBarLoading()
            // 数据成功后，停止下拉刷新
            wx.stopPullDownRefresh()
        }, 600);
    },
})
